Welcome to “Dynamic Routes.” After watching this video, you will be able
to: Describe how to call an external API in Flask Describe how to pass parameters to routes
in Flask Let's look at an example of how you might
call an external API in Flask. The easiest way is to use the Python requests
library. You can return the JSON from the external
API to your client. However, you can also process the results
before sending them back to your client. Here is an example, first, you import flask and request modules. The code here assumes you have already installed
the requests library. You can define your route next. Use the requests library to request the openlibrary
API and search for information for the author Michael Crichton. Store the response in a variable called res. Then check if the response’s status code
from the openlibrary API is 200. If the response is 200, you return the JSON
to the client. If the response happens to be 404, you send
a message, “Something went wrong." Finally, in this hypothetical case, if the
response is anything else, you return with a status of 500 and a message “Server error.” When developing RESTful APIs, you can send
some resource-id as part of the request URL. For example, you want to create an endpoint
that returns book information by International Standard Book Number (ISBN), but instead of
hard coding the ISBN, you want the client to send it as part of
the URL Flask provides dynamic routing for this purpose Let's look at a concrete example: Add the variable called isbn as a dynamic
part of the URL. Then pass this variable to the openlibrary
API. The result is then sent back to the client. Flask also allows you to set the parameter
type. The framework uses this information to validate
incoming requests. For example, you can create an endpoint of
terminals and SFO to get the number of terminals at the San Francisco airport. This route decorator triggers if the user
sends a string at the end of the URL. Similarly, in the previous example, you can
give ISBN to be a number. Here are some other examples of parameter
types in Flask. While string, int, and float are simple parameters,
you can also use complex ones like path to indicate a web path or a folder path
or Universal unique identifier (UUID) to indicate
a unique id like Globally Unique Identifier (GUID). Here is an example of UUID. You can create an endpoint, "network, “that
has a specific UUID to get information about the network. You can write this code where the route expects a variable uuid of type
uuid, the uuid is passed to the method as an argument, you return a success message if the uuid is
found, otherwise, you return an error code with an
appropriate message. In this video, you learned that: You can parse the Request Object to get query
parameters, body, and other arguments. You can set status on Response objects before
sending a response back to the client. You can use dynamic routes to create RESTful
endpoints.